<template> 
  <div>
    <el-upload :action="useOss ? ossUploadUrl + '' : minioUploadUrl + ''" list-type="picture" :multiple="false"
      :show-file-list="showFileList" :on-progress="onProgress" :file-list="fileList" :httpRequest="updload"
      :headers="{ 'Access-Control-Allow-Methods': 'put' }" :before-upload="beforeUpload" :on-remove="handleRemove"
      :on-error="error" :on-success="handleUploadSuccess" :on-preview="handlePreview">
      <el-button size="s米糕" type="primary" :disabled="disabled">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
      <div slot="video">
        <img :src="objURL" :autoplay="true" :controls="true" v-if="videoVisible" />
      </div>
    </el-upload>

    <el-progress v-show="showProcess" :percentage="processLen" :color="customColor" />


  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import axios from "axios"
import { ofSurplus } from "../../utils/withdrawalOfSurplus"
import { parseXML } from "../../utils/xml"
import { policy, UploadSegmentParamCheckFileHeader, uploadSegment, mergeSegment, listAlreadyUploadSegment } from "../../api/oss"
import { FILE_TYPE_VISIABLE } from "../../fileType/fileType"
import { deleteImage } from "../../api/oss"
export default {
  name: 'singleUpload',
  props: {
    replaceImage: {
      type: Function,
      default: (file) => {
        console.log("file", typeof file.url);

        if ("undefined" === typeof file.url) {
          return;
        }

        console.log("file.url", file.url);
        deleteImage(file.url);
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },

    value: String,
    ossUploadUrl: {
      type: String,
      default: 'http://obs.cn-east-3.myhuaweicloud.com'
    },
  },
  computed: {
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== '') {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    // fileList() {
    //   return [{
    //     name: this.imageName,
    //     url: this.imageUrl
    //   }]
    // },
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined;
      },
      set: function (newValue) {
      }
    }
  },
  data() {
    return {
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: '',
        // callback:'',
        token: ""
      },
      fileList: [
        {
          name: this.imageName,
          url: this.imageUrl
        }
      ],
      customColor: "#000FAD",
      processLen: 0,
      videoVisible: false,
      dialogVisible: false,
      showProcess: false,
      useOss: true, //使用oss->true;使用MinIO->false
      minioUploadUrl: 'http://localhost:8080/minio/upload',
      segmentData: {
        bucket: undefined,
        key: undefined,
        uploadId: undefined,
      },
      data: [],
      parNumber: 1,
      fileHeader: true,
      totalSize: 0,
      alreadySend: 0,
      objURL: undefined,
    };
  },

  created() {
    this.token = getToken();
  },
  methods: {
    /**
     * 
     * @param {Uint8Array} value 
     * @param {String} name 
     * @param {String} type 
     * @param {String} url
     */
    async uploadRemote(value, name, type, url) {
      let file = new File([value], name, { type: type });

      console.log("file", file, "url", url);

      return await axios.put(url, file, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      });
    },

    /**
     * @param {{}} option 
     * @param {String} content
     */
    mergeSegmentExec(option, content,) {
      // 合并段
      mergeSegment({
        fileName: option.file.name,
        uploadId: this.segmentData.uploadId
      }).then(url => {

        axios.post(url, content, {
          headers: {
            "Content-Type": "application/xml"
          }
        }).then(res => {

          this.objURL = url.substring(0, url.indexOf('?'));
          console.log("this.objURL:", this.objURL);
          option.onSuccess(this.objURL)

        });

      })
    },

    /**
     * 
     * @param {String} xml 
     */
    readAlreadyUploadSegment(xml) {

      let content = new String("<CompleteMultipartUpload>");

      let xmlPart = parseXML(xml);

      let collection = xmlPart.getElementsByTagName("Part");

      for (let index = 0; index < collection.length; index++) {
        const element = collection[index];
        let tag = element.getElementsByTagName("ETag")[0].textContent;
        tag = tag.substring(1, tag.length - 1);
        content = content.concat()
          .concat("<Part>")
          .concat("<PartNumber>")
          .concat(element.getElementsByTagName("PartNumber")[0].textContent)
          .concat("</PartNumber>")
          .concat("<ETag>")
          .concat(tag)
          .concat("</ETag>")
          .concat("</Part>");
      }

      content = content.concat("</CompleteMultipartUpload>")

      console.log("content", content);

      return content;

    },

    /**
     * 批量上传obs
     * @param {Array} data 
     */
    async batchUploadObs(data, res, option) {

      let sendSegment = new Uint8Array(data.length);

      for (let index = 0; index < data.length; index++) {
        sendSegment[index] = data[index];
      }
      return await this.uploadRemote(sendSegment, option.file.name, option.file.type, res);
    },

    /**
     * 批量上传
     * @param {{}} option 
     * @param {Array} data 
     */
    async batchUploadSegment(option, data) {
      let res = await uploadSegment({
        fileName: option.file.name,
        partNumber: this.parNumber,
        uploadId: this.segmentData.uploadId
      });
      console.log("this.parNumber front", this.parNumber);

      let result = await this.batchUploadObs(data, res, option);

      console.log("batchUploadSegment", result);

      this.parNumber++;

      console.log("this.parNumber after", this.parNumber);
      return result;
    },

    /**
     * @param {ReadableStreamDefaultReader} fileReaderStream
     * @param {{
     * value: Uint8Array,
     * done: boolean
     * }} data 
     */
    async readerStreamData(data, fileReaderStream, option, totalNUmber) {
      option.onProgress(option.file);
      if (data.done) { // 读取完毕

        if (0 != this.data.length) {
          let result = await this.batchUploadSegment(option, this.data);

          console.log("result: 上传成功", result);
        }
        let url = await listAlreadyUploadSegment({
          fileName: option.file.name,
          uploadId: this.segmentData.uploadId
        });

        let list = await axios.get(url);

        let conent = this.readAlreadyUploadSegment(list.data);

        // console.log("list", list);

        this.mergeSegmentExec(option, conent);
        fileReaderStream.closed.then(res => {
          console.log("closed", res);
        });
        fileReaderStream.releaseLock();
        
        this.data = [];
        return;
      }

      data.value.forEach(e => {
        this.data.push(e);
      });

      if (102400 > this.data.length) {
        return fileReaderStream.read().then((res) => this.readerStreamData(res, fileReaderStream, option, totalNUmber));
      }

      if (this.fileHeader) {
        let resultHeader = [];
        for (let index = 0; index < 16; index++) {
          resultHeader[index] = this.data[index];
        }
        let res = await UploadSegmentParamCheckFileHeader({
          fileName: option.file.name,
          partNumber: 1,
          byteData: resultHeader,
          uploadId: this.segmentData.uploadId
        });
        console.log("res-----------", res);

        let rmoteData = await this.batchUploadObs(this.data, res, option);

        // console.log("rmoteData", rmoteData);
        this.parNumber = 2;
        this.fileHeader = false;

      } else {
        let remoteData = await this.batchUploadSegment(option, this.data);
        // console.log("remoteData", remoteData);
      }
      this.data = [];

      return fileReaderStream.read().then((res) => this.readerStreamData(res, fileReaderStream, option, totalNUmber));
    },
    /**
     * @param {{
     * action :String,
     * data: undefined,
     * file: File,
     * headers: {},
     * onError: Function,
     * onProgress: Function,
     * onSuccess: Function,
     * withCredentials: boolean
     * }
     * } option 

     */
    updload(option) {
    
      let totalNUmber = ofSurplus(option.file.size, 1048576);


      /**
       * @param {ReadableStream}  stream
       */
      let stream = option.file.stream();
     
      /**
       * @param {ReadableStreamGetReaderOptions}
       * */
      let fileReaderStream = stream.getReader();

      this.totalSize = option.file.size;
      fileReaderStream.read().then((res) => this.readerStreamData(res, fileReaderStream, option, totalNUmber));
    },


    onProgress(event, file, fileList) {

      let second = file.size / 1024000;

      let intervalSecond = second / 100 * 1000;
      console.log("intervalSecond", intervalSecond);
      this.showProcess = true;

      let intvalId = setInterval(() => {

        if ("success" == file.status) {
          this.processLen = 100;
          this.showProcess = false;
          clearInterval(intvalId);
          return;
        }

        if (this.processLen < 100) {
          this.processLen++;
          return;
        }


      }, intervalSecond);
      console.log(event, file, fileList)

    },

    error(err, file, fileList) {
      Message({
        message: err,
        type: 'error',
        duration: 3 * 1000
      })
    },

    emitInput(val) {
      console.log("val", val)
      this.$emit('input', val)
    },
    handleRemove(file, fileList) {
      console.log("file123", file);
      this.replaceImage(file);
      this.emitInput('');
    },
    handlePreview(file) {

      let suffix = file.name.substr(file.name.indexOf("."));

      if (!FILE_TYPE_VISIABLE.hasOwnProperty(suffix)) {
        return;
      }

      this[FILE_TYPE_VISIABLE[suffix]] = true;

    },
    async beforeUpload(file) {

      console.log("file", file);

      let res = await policy(file.name);

      console.log("res", res);

      let segment = await axios.post(res, null, {});
      console.log("segment", segment);
      let obj = parseXML(segment.data);
      console.log("obj", obj.getElementsByTagName("UploadId"), {
        fileName: file.name,
        uploadId: obj.getElementsByTagName("UploadId")[0],
        parNumber: 1
      });

      this.segmentData = {
        bucket: obj.getElementsByTagName("Bucket")[0].textContent,
        uploadId: obj.getElementsByTagName("UploadId")[0].textContent,
        key: obj.getElementsByTagName("Key")[0].textContent
      }
      return true;
    },

    /**
     * 
     * @param {String} ordImage 
     * @param {String} youngImage 
     */
    deleteFile(ordImage, youngImage) {
      
      console.log("ordImage", ordImage, "youngImage", youngImage);
      if (ordImage == youngImage) {
        return;
      }
      this.replaceImage({url:ordImage})
    },

    handleUploadSuccess(res, file) {

      Message({
        message: "上传成功",
        duration: 3 * 1000,
        type: "success"
      })

      console.log("res", res, "file", file)

      this.showFileList = true;
      let image = this.fileList.pop();

      this.fileList.push({ name: file.name, url: res });
      this.deleteFile(image.url, res);
      this.emitInput(this.fileList[0].url);

      this.$emit("fileReceive", file);
    }
  }
}
</script>
<style>

</style>
